package com.jiuyin.dianjing.ui.fragment.team;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.DividerItemDecoration;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.jiuyin.dianjing.R;
import com.jiuyin.dianjing.adapter.BaseRecyclerAdapter;
import com.jiuyin.dianjing.adapter.SmartViewHolder;
import com.jiuyin.dianjing.api.base.DefaultApiResult;
import com.jiuyin.dianjing.api.constant.ApiConstant;
import com.jiuyin.dianjing.api.enums.ApiEnum;
import com.jiuyin.dianjing.api.interfaces.ApiResultCallback;
import com.jiuyin.dianjing.api.server.ServerApi;
import com.jiuyin.dianjing.app.HelperApplication;
import com.jiuyin.dianjing.event.RefreshEvent;
import com.jiuyin.dianjing.model.TeamMember;
import com.jiuyin.dianjing.ui.activity.team.ManagerSetActivity;
import com.jiuyin.dianjing.ui.activity.team.TeamMembersActivity;
import com.jiuyin.dianjing.ui.fragment.base.BaseFragment;
import com.jiuyin.dianjing.util.DisplayUtil;
import com.yanzhenjie.recyclerview.OnItemMenuClickListener;
import com.yanzhenjie.recyclerview.SwipeMenuItem;
import com.yanzhenjie.recyclerview.SwipeRecyclerView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;

import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_PART;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_TEAMID;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_TOKEN;


/**
 * 成员管理
 */
public class TeamMembersFragment extends BaseFragment implements TeamManageDialogFragment.ItemClickListener {
    public static final String TYPE = "param1";
    public static final int TYPE_DEFAULT = 0;
    public static final int TYPE_HANDED_OVER = 1;
    @BindView(R.id.rv_members)
    SwipeRecyclerView swipeRecyclerView;
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.iv_rightMenu)
    ImageView ivRightMenu;
    private int mType;
    private int mPart;
    private String mTeamId;
    private ArrayList<TeamMember> mDataList = new ArrayList<>();
    private BaseRecyclerAdapter<TeamMember> adapter;

    public static TeamMembersFragment newInstance(int type, String teamId, int part) {
        TeamMembersFragment fragment = new TeamMembersFragment();
        Bundle args = new Bundle();
        args.putInt(TYPE, type);
        args.putString(KEY_TEAMID, teamId);
        args.putInt(KEY_PART, part);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected int setLayoutId() {
        return R.layout.fragment_team_members;
    }

    @Override
    protected void initData() {
        if (getArguments() != null) {
            mType = getArguments().getInt(TYPE, TYPE_DEFAULT);
            mTeamId = getArguments().getString(KEY_TEAMID);
            mPart = getArguments().getInt(KEY_PART, 10);
        }
    }

    @Override
    protected void initView() {
        ivBack.setVisibility(View.VISIBLE);
        ivBack.setOnClickListener(v -> getActivity().onBackPressed());
        if (mType == TYPE_DEFAULT) {
            tvTitle.setText("全部成员");
            int width = getResources().getDimensionPixelSize(R.dimen.dp_70);
            swipeRecyclerView.setSwipeMenuCreator((leftMenu, rightMenu, position) -> {
                if (mDataList.get(position).member_id.equals(HelperApplication.getUserId())) {
                    return;
                }
                if (mDataList.get(position).part - mPart <= 0) {
                    return;
                }
                SwipeMenuItem deleteItem = new SwipeMenuItem(getContext())
                        .setBackground(R.drawable.selector_red)
                        .setImage(R.drawable.ic_action_delete)
                        .setText("移除")
                        .setTextColor(Color.WHITE)
                        .setWidth(width)
                        .setHeight(ViewGroup.LayoutParams.MATCH_PARENT); // 各种文字和图标属性设置。
                rightMenu.addMenuItem(deleteItem); // 在Item右侧添加一个菜单。
            });
            OnItemMenuClickListener mItemMenuClickListener = (menuBridge, adapterPosition) -> {
                // 任何操作必须先关闭菜单，否则可能出现Item菜单打开状态错乱。
                menuBridge.closeMenu();
                // 菜单在Item中的Position：
                int menuPosition = menuBridge.getPosition();
                final TeamMember teamMember = mDataList.get(adapterPosition);
                new AlertDialog.Builder(getContext())
                        .setMessage("确定移除？")
                        .setNegativeButton("取消", null)
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                doDelete(teamMember.member_id);
                                mDataList.remove(adapterPosition);
                                adapter.notifyItemRemoved(adapterPosition);
                            }
                        })
                        .show();
            };
            // 菜单点击监听。
            swipeRecyclerView.setOnItemMenuClickListener(mItemMenuClickListener);
        } else if (mType == TYPE_HANDED_OVER) {
            tvTitle.setText("移交战队");
            swipeRecyclerView.setOnItemClickListener((view, adapterPosition) -> {
                TeamMember model = mDataList.get(adapterPosition);
                if (model.part == 0) {//队长
                    return;
                }
                new AlertDialog.Builder(getContext())
                        .setMessage("确定选择" + model.nickname + "为新队长,你将自动放弃队长管理身份。")
                        .setNegativeButton("取消", null)
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                HashMap hashMap = new HashMap();
                                hashMap.put("memberId", model.member_id);
                                hashMap.put(KEY_TEAMID, mTeamId);
                                hashMap.put(KEY_TOKEN, HelperApplication.getToken());
                                JSONObject data = new JSONObject(hashMap);
                                ApiResultCallback requestCallback = new DefaultApiResult() {
                                    @Override
                                    public void onSuccess(JsonObject data) {
                                        Intent intent = new Intent(getContext(), TeamMembersActivity.class);
                                        intent.putExtra(KEY_TEAMID, mTeamId);
                                        intent.putExtra(KEY_PART, ApiConstant.VALUE_PART_MEMBER);
                                        startActivity(intent);
                                        getActivity().finish();
                                    }
                                };
                                ServerApi.post(ApiEnum.TRANSFER_THE_CAPTAIN, data, null, progress, d -> addDisposable(d), requestCallback);
                            }
                        }).show();
            });
        }

        swipeRecyclerView.addItemDecoration(new DividerItemDecoration(getContext(), DividerItemDecoration.VERTICAL));
        adapter = new BaseRecyclerAdapter<TeamMember>(mDataList, R.layout.item_team_member) {
            @Override
            protected void onBindViewHolder(SmartViewHolder holder, TeamMember model, int position) {
                ImageView ivHead = holder.itemView.findViewById(R.id.iv_head);
                Glide.with(getContext())
                        .load(model.header)
                        .override(DisplayUtil.dp2px(getContext(), 26.7f))
                        .into(ivHead);
                holder.text(R.id.tv_name, model.nickname);
                ImageView ivJob = holder.itemView.findViewById(R.id.iv_job);
                //0队长 1管理员 2 成员
                switch (model.part) {
                    case 0:
//                        ivHead.setImageResource(R.drawable.duizhang);
                        ivJob.setVisibility(View.VISIBLE);
                        ivJob.setImageResource(R.drawable.duizhang);
                        break;
                    case 1:
//                        ivHead.setImageResource(R.drawable.guanliyuan);
                        ivJob.setVisibility(View.VISIBLE);
                        ivJob.setImageResource(R.drawable.guanliyuan);
                        break;
                    default:
                        ivJob.setVisibility(View.GONE);
                        break;
                }
                if (model.member_id.equals(HelperApplication.getUserId())) {
                    holder.visible(R.id.tv_me);
                } else {
                    holder.gone(R.id.tv_me);
                }
            }
        };
        swipeRecyclerView.setAdapter(adapter);
    }

    private void doDelete(String memberId) {
        HashMap hashMap = new HashMap();
        hashMap.put("member_id", memberId);
        hashMap.put(KEY_TEAMID, mTeamId);
        JSONObject data = new JSONObject(hashMap);
        ApiResultCallback requestCallback = new DefaultApiResult() {
            @Override
            public void onSuccess(JsonObject data) {

            }
        };
        ServerApi.post(ApiEnum.KICK_OUT_TEAM_MEMBER, data, null, progress, d -> addDisposable(d), requestCallback);
    }

    @Override
    public void fetchData() {
        HashMap hashMap = new HashMap();
        hashMap.put(KEY_TEAMID, mTeamId);
        hashMap.put(KEY_TOKEN, HelperApplication.getToken());
        JSONObject data = new JSONObject(hashMap);
        ApiResultCallback callback = new DefaultApiResult() {

            @Override
            public void onSuccess(JsonObject data) {
                List<TeamMember> members = new Gson().fromJson(data.getAsJsonArray("memberList"),
                        new TypeToken<List<TeamMember>>() {
                        }.getType());
                if (null != mDataList) {
                    setRightMenu();
                    mDataList.clear();
                    mDataList.addAll(members);
                    adapter.refresh(mDataList);
                }
            }
        };
        ServerApi.post(ApiEnum.GET_TEAM_MEMBER_LIST, data, null, progress, d -> addDisposable(d), callback);
    }

    @Override
    public void onSetManagerClick() {
        Intent intent = new Intent(getContext(), ManagerSetActivity.class);
        intent.putParcelableArrayListExtra("members", mDataList);
        startActivity(intent);
    }

    @Override
    public void onGiveUpClick() {
        getActivity().getSupportFragmentManager().beginTransaction()
                .hide(this)
                .add(R.id.nav_host_fragment, TeamMembersFragment.newInstance(TYPE_HANDED_OVER, mTeamId, mPart))
                .addToBackStack(null)
                .commit();
    }

    /**
     * 设置右边的菜单栏
     */
    private void setRightMenu() {
        if (mType == TYPE_DEFAULT) {
            tvTitle.setText("全部成员");
            if (mPart <= 1) {
                ivRightMenu.setVisibility(View.VISIBLE);
                ivRightMenu.setImageResource(R.drawable.duiyuan_setting);
                ivRightMenu.setOnClickListener(v -> {
                    TeamManageDialogFragment.newInstance(mPart, mTeamId)
                            .setItemClickListener(this)
                            .show(getChildFragmentManager(), null);
                });
            }
        }
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = super.onCreateView(inflater, container, savedInstanceState);
        EventBus.getDefault().register(this);
        return view;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(RefreshEvent event) {
        if (event.clazzName.equals(getClass().getSimpleName())) {
            fetchData();
        }
    }
}
